 ///
 /// @file    Singleton1.cc
 /// @author  lemon(haohb13@gmail.com)
 /// @date    2023-04-28 14:51:19
 ///
 
#include <iostream>
using std::cout;
using std::endl;

//需求：单例对象能自动回收
//解决方案一：嵌套类 + 静态对象


//AutoRelease类专为Singleton而生,
//既然这样，就可以考虑将其设计为嵌套类
class Singleton
{
	class AutoRelease
	{
	public:
		AutoRelease()
		{	cout << "AutoRelease()" << endl;	}

		~AutoRelease() {
			cout << "~AutoRelease()" << endl;
			//静态数据成员可以在嵌套类中直接访问
			if(_pInstance) {
				delete _pInstance;
				_pInstance = nullptr;
			}
		}
	};
public:
	static Singleton * getInstance()
	{
		if(nullptr == _pInstance) {
			_pInstance = new Singleton();
		}
		return _pInstance;
	}

	static void destroy()
	{
		if(_pInstance) {
			delete _pInstance;
			_pInstance = nullptr;
		}
	}

private:
	Singleton() {	cout << "Singleton()" << endl;	}
	~Singleton() {	cout << "~Singleton()" << endl;	}

	friend class AutoRelease;
private:
	static Singleton * _pInstance;
	static AutoRelease _ar;
	int _data;
};

Singleton * Singleton::_pInstance = nullptr;
//在类之外进行初始
Singleton::AutoRelease Singleton::_ar;

 
void test0() 
{
	Singleton * p1 = Singleton::getInstance();
	Singleton * p2 = Singleton::getInstance();
	cout << "p1:" << p1 << endl;
	cout << "p2:" << p2 << endl;
} 
 
int main(void)
{
	test0();
	return 0;
}
